<template>
  <el-dialog
    @close="close"
    title="添加&修改博客信息"
    :visible.sync="dialog"
    width="60%"
    >
    <el-form size="mini" :model="formInline" :rules="rules" ref="formInline" label-width="80px">
      <el-form-item label="标题：" prop="title" >
        <el-input v-model="formInline.title"></el-input>
      </el-form-item>

      <el-form-item label="介绍：" prop="introduction" >
        <el-input v-model="formInline.introduction"></el-input>
      </el-form-item>

      <el-form-item label="正文：" prop="content">
        <!-- 图片上传组件辅助-->
        <el-upload
          class="avatar-uploader2"
          :action="uploadUrl"
          name="fileName"
          :headers="token"
          :show-file-list="false"
          :on-success="uploadSuccessEdit"
          :before-upload="beforeUploadEdit">
        </el-upload>
        <div>
          <quill-editor class="ql-editor" v-model="formInline.content" ref="myQuillEditor" style="height: 300px;" :options="editorOption">
          </quill-editor>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :disabled="btnLoading" @click="dialog = false">取 消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>

</template>
<script>
  // 工具栏配置
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],

    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction

    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],

    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image', 'video'],
    ['clean']                                         // remove formatting button
  ]
import { addBlogApI,updateBlogApI } from '@/api/blog'
import { quillEditor } from 'vue-quill-editor'; //调用编辑器
  import { getToken } from '@/utils/auth' //
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
// import { getRouterTreeAPI } from '@/api/system/menu'

export default {
  name: 'BlogEdit',
  components: { quillEditor },
  props: {
    dialog_: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: null
    },
    model: {  // 编辑传入的对象
      default: null,
      type: Object
    }
  },
  data() {
    var validateSort = (rule, value, callback) => {``
      var reg = /^[0-9]\d*$/
      if (value === null || value === '' | value === undefined) {
        callback()
      } else if (!reg.test(value)) {
        return callback(new Error('请输入正确的数字'))
      } else {
        callback()
      }
    }
    return {
      props: {
        label: 'title',
        children: 'children'
      },
      token:{
        Authorization:getToken()
      },
      uploadUrl:  this.UPLOADURL,
      dialog: false,
      formInline: {
        id:'',
        title:'',
        content:'',
        introduction:'',
        type:1
      },
      btnLoading: false,
      requireUpload:false,
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      editorOption: {
        placeholder: '',
        theme: 'snow',  // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.avatar-uploader2 input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      treeData: [],
      rules: {
        name: [
          { required: true, message: '请填写角色名称', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请填写角色描述', trigger: 'blur' }
        ],
        sort: [
          { validator: validateSort, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 上传图片前
    beforeUploadEdit(res, file) {
      // 显示loading动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccessEdit(res, file) {
      debugger
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      if (res.rtnInfo.code == 0) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.data.url为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.rtnInfo.data[0]
        )
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    close() {
      this.$emit('close')
    },
    // 提交
    onSubmit() {
      this.$refs.formInline.validate((valid) => {
        if (valid) {
          if(this.model){//修改
            this.btnLoading = true
            this.formInline.id = Number(this.formInline.id)
            updateBlogApI(this.formInline).then(res => {
              this.btnLoading = false
              if (res.code === 200) {
                this.$message.success('操作成功')
                this.$emit('success')
              } else {
                this.$message.error(res.message)
              }
            })
          }else{ //增加
            this.btnLoading = true
            addBlogApI(this.formInline).then(res => {
              this.btnLoading = false
              if (res.code === 200) {
                this.$message.success('操作成功')
                this.$emit('success')
                this.dialogadd = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
        } else {
          this.$message.warning("请填写完整的信息")
          return false;
        }
      });

    },
  },
  mounted() {
    debugger
    this.dialog = this.dialog_
    if (this.model != '' && this.model != null){
      this.formInline = this.model
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  }
}
</script>
